package com.yl.applicationsecurity.utils;

/**
 * @author 鹤仙问鹿仙
 * @program: Application-security
 * @description:
 * @date 2025-01-26 11:35:41
 */
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RASPClient {

    private static String app_key="lq2t*SfqAi$JKmI$HhCjO85XTUQndllk";
    private static String app_secret="547bmAkr^Rmh%WJeiPfEDUYhLGm~5JUL";

    // 生成 API 签名
    public static Map<String, String> generateApiSignature(String appKey, String appSecret, String method, String uri) throws Exception {
        // 生成时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());

        // 拼接 string-to-sign
        String stringToSign = appKey + timestamp + method + uri;
        System.out.println(stringToSign);

        // 使用 HmacSHA1 算法计算签名
        String sign = calculateHMACSHA1(stringToSign, appSecret);

        // 构建 Authorization 字段
        String authorization = appKey + "." + timestamp + "." + sign;

        // 返回时间戳和签名
        Map<String, String> result = new HashMap<>();
        result.put("timestamp", timestamp);
        result.put("sign", sign);
        result.put("authorization", authorization);
        return result;
    }

    // 使用 HmacSHA1 计算签名
    public static String calculateHMACSHA1(String data, String key) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(secretKeySpec);
        byte[] bytes = mac.doFinal(data.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    // 调用 RASP 接口获取列表
    public static List<String> getRasplist(String authorization) throws Exception {
        List<String> rasplist = new ArrayList<>();
        int page = 0;
        while (true) {
            String url = "https://10.33.155.76:443/oapi/processes?page=" + page + "&size=1000";
            String response = sendGetRequest(url, authorization);
            JSONObject jsonResponse = JSONObject.parseObject(response);
            JSONArray data = jsonResponse.getJSONArray("data");

            if (data == null || data.size() == 0) {
                break;
            }

            for (int i = 0; i < data.size(); i++) {
                JSONObject item = data.getJSONObject(i);
                JSONObject containerInfo = item.getJSONObject("containerInfo");
                if (containerInfo != null && !containerInfo.getString("name").isEmpty()) {

                    rasplist.add(containerInfo.getString("name"));
                }
            }

            page++;
        }
        return rasplist;
    }

    // 使用 Java 原生方法发送 GET 请求，并禁用 SSL 验证
    private static String sendGetRequest(String urlStr, String authorization) throws Exception {
        // 禁用 SSL 验证
        disableSSLVerification();

        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0");
        connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("Authorization", authorization);
        connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        //connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        connection.setRequestProperty("Upgrade-Insecure-Requests", "1");
        // 获取响应的字符编码（如果没有则默认使用 UTF-8）
        String encoding = connection.getContentEncoding();
        if (encoding == null) {
            encoding = "UTF-8";  // 默认为 UTF-8
        }



        // 获取响应输入流，并使用正确的字符编码读取
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));

        // 读取响应内容
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();


    }

    // 禁用 SSL 验证
    private static void disableSSLVerification() throws NoSuchAlgorithmException {
        try {
            // 创建信任所有证书的 TrustManager
            TrustManager[] trustAllCertificates = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            // 设置 SSLContext 和 HostnameVerifier
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCertificates, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 禁用主机名验证
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
        } catch (Exception e) {
            throw new NoSuchAlgorithmException("SSL verification disabling failed", e);
        }
    }

    public static List<String>  getData() throws Exception {
        Map<String, String> signature = generateApiSignature(app_key, app_secret, "GET", "/oapi/processes");
        String authorization = signature.get("authorization");

        // 获取 RASP 列表
        List<String> rasplist = getRasplist(authorization);
        return rasplist;
    }


    public static void main(String[] args) {


        try {
            // 获取 API 签名
            Map<String, String> signature = generateApiSignature(app_key, app_secret, "GET", "/oapi/processes");
            String authorization = signature.get("authorization");

            // 获取 RASP 列表
            List<String> rasplist = getRasplist(authorization);
            System.out.println("RASP List: " + rasplist.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
